package com.upb.webserver.chainhost;

import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.MybatisExampleTools;
import com.upb.webserver.dao.entity.TbChainHost;
import com.upb.webserver.dao.entity.TbChainHostExample;
import com.upb.webserver.dao.entity.TbHost;
import com.upb.webserver.dao.mapper.TbChainHostMapper;
import com.upb.webserver.dao.mapper.TbHostMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ChainHostManager {
    @Autowired
    private TbChainHostMapper chainHostMapper;
    @Autowired
    private TbHostMapper hostMapper;


    /**
     * @param hostId
     * @return
     */
    public long countByHostId(int hostId) {
        log.info("start exec method [countByHostId]. hostId:{}", hostId);
        TbChainHostExample example = MybatisExampleTools.initSampleExample(TbChainHostExample.class, new TbChainHost(hostId));
        Long count = chainHostMapper.countByExample(example);
        log.info("success exec method [countByHostId]. result:{}", count);
        return count;
    }

    /**
     * @param hostId
     */
    @Deprecated
    public void verifyHostIdNotInUse(int hostId) {

        //cancel this limit
        if (1 == 1) {
            return;
        }

        log.info("start exec method [verifyHostIdNotInUse]. hostId:{}", hostId);
        if (countByHostId(hostId) > 0) {
            log.warn("fail exec method[verifyHostIdNotInUse]. found chain record by hostId:{}", hostId);
            TbHost tbHost = hostMapper.selectByPrimaryKey(hostId);
            throw new WebServerException(ConstantCode.HOST_HAD_BEAN_IN_USE.msg(String.format("【id:%1d ip:%2s】 has bean in use", hostId, tbHost.getIp())));
        }
        log.info("success exec method [verifyHostIdNotInUse]. hostId:{}", hostId);
    }

}
